package gov.pbc.nn.kjgl.software.view;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import gov.pbc.nn.core.entity.BaseEntity;
import gov.pbc.nn.kjgl.entity.Project;
import gov.pbc.nn.kjgl.entity.ProjectMember;
import gov.pbc.nn.kjgl.software.dao.ProjectMangeDao;
import gov.pbc.nn.kjgl.software.dao.ProjectMangeJdbcCoreDao;
import gov.pbc.nn.kjgl.software.dao.ProjectMangeJdbcDao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

@Component("projectMangePR")
public class ProjectMangePR {

	@Autowired
	private ProjectMangeDao projectMangeDao;

	@Autowired
	private ProjectMangeJdbcDao projectMangeJdbcDao;
	
	@Autowired
	private ProjectMangeJdbcCoreDao projectMangeJdbcCoreDao;


	@DataProvider
	public void getProjectMenberByPid(Page<ProjectMember> page, Map<String, Object> parameter) {
		if (parameter != null) {
			projectMangeDao.getProjectMenberByPid(page, (String) parameter.get("pid"));
		}
	}

	@DataProvider
	public List<Map<String, Object>> getAll(Page<Map<String, Object>> page, String username) {
		return projectMangeJdbcCoreDao.getAll(page, username);
	}
	
	@DataProvider
	public void getAllPage(Page<Project> page, Criteria criteria) {
		projectMangeJdbcDao.getAllPage(page, criteria);

	}

	@Expose
	@Transactional
	public void saveAll(Map<String, Object> parameter) {
		ProjectMember p = new ProjectMember();
		//System.out.println(parameter.get("projectrole"));
		p.setProjectRole(Integer.parseInt((String) parameter.get("projectrole")));
		p.setUsername((String) parameter.get("username"));
		p.setPhone((String) parameter.get("phone"));
		p.setProjectId((String) parameter.get("projectid"));
		projectMangeDao.saveProjectMember(p);
	}

	@Expose
	@Transactional
	public void deleteProjectMember(List<String> ids) {
		for (String id : ids) {
			projectMangeDao.deletePMember(id);
		}

	}
	@Transactional
	@DataResolver
	public void saveProjectMember(List<ProjectMember> pms) throws Exception{
		for(ProjectMember p:pms){
			this.saveEntity(p);
		}
	}
	
	private void saveEntity(BaseEntity entity) throws Exception {
		EntityState state = EntityUtils.getState(entity);
		if (state.equals(EntityState.NEW)) {
			this.projectMangeDao.save(entity);
		} else if (state.equals(EntityState.MODIFIED)) {
			this.projectMangeDao.update(entity);
		} else if (state.equals(EntityState.DELETED)) {
			this.projectMangeDao.delete(entity);
		}
	}
}
